import React, { Component } from 'react'
import {
  Text,
  View,
  Image,
  StyleSheet,
  DeviceEventEmitter,
  StatusBar,
  Platform,
  PixelRatio,
  ScrollView,
  Dimensions,
  AlertIOS,
  Animated,
  RefreshControl,
  TouchableOpacity,
  TouchableWithoutFeedback,
  VirtualizedList,
  FlatList,
  Modal,
} from 'react-native'
import Immutable from 'immutable'
import Icon from 'react-native-vector-icons/Ionicons'

import GoodsItem from '../component/GoodsItem'
import SkuSelecter from '../component/SkuSelecter'
import Empty from '../component/Empty'
import ShopBar from '../component/ShopBar'
import Base from './Base'
import Search from './Search'
import {
  NavigationActions,
  createAction,
  px2dp,
  accAdd,
  accSub,
  getAsyncStorage,
} from '../utils'
import { toast } from '../utils/toast'
import * as productService from '../services/product'
import * as cartService from '../services/cart'

const isIOS = Platform.OS == 'ios'
const { width, height } = Dimensions.get('window')
const MAIN_HEIGHT = height - (Platform.OS === 'ios' ? 64 : 42) - 36
const LABEL_HEIGHT = 25

const headH = px2dp(isIOS ? 120 : 100)
const InputHeight = px2dp(28)

const cellWH = width / 2
const borderWidth = (Platform.OS === 'ios' ? 1.0 : 1.0) / PixelRatio.get()

class GoodsList extends Base {
  constructor(props) {
    super(props)
    this.state = {
      modalVisible: false,
      modalType: '',
      modalTitle: '',
      skus: [],
      records: [],
      totalPrice: 0,
      keywords: '',
      requestTimes: 0,
    }
    this.subscription = null
  }
  openSearch() {
    this.setState({ modalType: 'search', modalVisible: true })
  }
  closeSearch() {
    this.setState({ modalType: '', modalVisible: false })
  }
  search(keywords) {
    this.closeSearch()
    this.loadData('', '', keywords)
  }
  loadData(caid, cbid, keywords) {
    this.setState({ fetching: true })

    if (!caid) {
      caid = 0
    }
    if (!cbid) {
      cbid = 0
    }
    if (!keywords) {
      keywords = ''
    } else {
      this.props.navigation.setParams({ keywords })
    }
    const { requestTimes } = this.state
    productService
      .list({ caid, cbid, keywords })
      .then(data => {
        // load cart data
        this.loadCart(cartData => {
          this.setState({
            requestTimes: requestTimes + 1,
            fetching: false,
            refreshing: false,
            keywords,
            records: data.records,
            pages: data.pages,
            current: data.current,
            totalPrice: cartData.totalPrice,
          })
        })
      })
      .catch(e => {
        this.checkError(e)
      })
  }
  onRefresh() {
    const { caid, cbid } = this.props.navigation.state.params
    const { keywords } = this.state
    this.setState({ refreshing: true })
    setTimeout(() => {
      this.loadData(caid, cbid, keywords)
    }, 1000)
  }
  onEndReached(info) {
    const { pages, current, type, records, fetching } = this.state
    if (fetching) {
      return
    }
    const pageNum = current + 1
    if (pageNum > pages) {
      return
    }
    this.setState({ fetching: true })
    const { caid, cbid } = this.props.navigation.state.params
    let { keywords } = this.state
    if(!keywords){
      keywords=''
    }
    productService
      .list({ caid, cbid, keywords, current: pageNum })
      .then(data => {
        if (data.current == current) {
          this.setState({ fetching: false })
          return
        }
        const list = records.concat(data.records)
        this.setState({
          fetching: false,
          records: list,
          pages: data.pages,
          current: data.current,
        })
      })
      .catch(e => {
        this.checkError(e)
      })
  }

  loadCart(fn) {
    cartService.queryLocal().then(data => {
      // 数据处理
      let str = ''
      let unchecked = ''
      data.map((item, i) => {
        // 获取未被选中的item
        if (!item.checked) {
          unchecked += `${item.id}#`
        }
        str += `|${item.id}#${item.num}`
      })
      cartService
        .view({ data: str, unchecked })
        .then(data => {
          if (!fn) {
            this.setState({
              totalPrice: data.totalPrice,
            })
          } else {
            fn(data)
          }
        })
        .catch(e => {
          this.checkError(e)
        })
    })
  }
  saveCart(item) {
    if (!item.stock || item.stock <= 0) {
      toast('该商品库存不足')
      return
    }
    const params = {
      id: item.id,
      checked: true,
      num: 1,
    }
    cartService.writeLocal(params).then(data => {
      // 发送刷新事件
      DeviceEventEmitter.emit('cart.reload', 'goodsList')
      this.loadCart()
    })
  }
  onCart(item) {

    // 获取sku
     getAsyncStorage('STOREID')
    .then(storeId => {

      productService
        .skus({ id: item.id,storeId })
        .then(data => {

          // 弹出选择框
          this.setState({
            skus: data,
            modalVisible: true,
            modalType: 'sku',
            modalTitle: item.name,
          })
        })
        .catch(e => {
          this.checkError(e)
        })
    })
    .catch(e => {
      // error
      this.checkError({ msg: '位置不在服务范围内' })
    })
  }
  onEvent() {
    this.loadCart(data => {
      this.setState({
        totalPrice: data.totalPrice,
      })
    })
  }
  renderSkuSelecter() {
    const { skus } = this.state

    return (
      <View
        style={{
          backgroundColor: 'white',
          paddingHorizontal: 15,
          paddingVertical: 20,
          borderRadius: 3,
        }}
      >
        return skus.map((item,i)=>{<Text key={i}>{item.name}</Text>})
      </View>
    )
  }
  renderCart() {
    const { totalPrice } = this.state
    return (
      <Animated.View style={[styles.iconView]}>
        <TouchableOpacity
          style={styles.iconViewWrap}
          onPress={() => this.goto('CartSingle')}
        >
          <Icon name="ios-cart-outline" size={22} style={{ color: '#444' }} />
          <View
            style={[
              styles.count,
              {
                transform: [{ translateX: totalPrice > 0 ? 0 : -9999 }],
              },
            ]}
          >
            <Text style={{ fontSize: 10, color: '#fff' }}>¥{totalPrice}</Text>
          </View>
        </TouchableOpacity>
      </Animated.View>
    )
  }

  renderItem = ({ item, index }) => {
    let borderRightWidth = 0
    let top = 0
    if (index % 2 == 0) {
      borderRightWidth = borderWidth
    }
    if (index < 2) {
      top = 10
    }
    const goodsId = item.id
    return (
      <GoodsItem
        key={index}
        item={item}
        width={cellWH}
        top={top}
        borderRightWidth={borderRightWidth}
        onCartPress={() => this.onCart(item)}
        onPress={() => this.goto('Goods', { goodsId })}
      />
    )
  }
  componentWillUnmount() {
    this.subscription.remove()
  }
  componentDidMount() {
    const { caid, cbid, keywords } = this.props.navigation.state.params
    this.props.navigation.setParams({
      openSearch: () => this.openSearch(),
      keywords,
    })
    this.subscription = DeviceEventEmitter.addListener(
      'cart.reload',
      this.onEvent.bind(this)
    )
    this.loadData(caid, cbid, keywords)
  }
  render() {
    const {
      requestTimes,
      fetching,
      refreshing,
      records,
      skus,
      modalType,
      modalTitle,
    } = this.state

    return (
      <View style={styles.container}>
        <StatusBar barStyle="default" />
        {requestTimes > 0 && records.length == 0 ? (
          <Empty />
        ) : (
          <FlatList
            refreshing={refreshing || false}
            numColumns={2}
            horizontal={false}
            keyExtractor={(item, index) => String(index)}
            data={records}
            renderItem={this.renderItem}
            onRefresh={() => this.onRefresh()}
            onEndReached={info => this.onEndReached(info)}
            onEndReachedThreshold={0.15}
          />
        )}
        {requestTimes > 0 && records.length == 0 ? null : this.renderCart()}
        <Modal
          animationType={modalType == 'search' ? 'slide' : 'fade'}
          transparent
          onRequestClose={() => {}}
          visible={this.state.modalVisible}
        >
          {modalType == 'search' ? (
            <Search
              onCancel={() => this.closeSearch()}
              onSearch={keywords => this.search(keywords)}
            />
          ) : (
            <SkuSelecter
              data={skus}
              title={modalTitle}
              onCancel={() => this.closeSearch()}
              onOk={item => {
                this.saveCart(item)
                this.closeSearch()
              }}
            />
          )}
        </Modal>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f0f0f0',
  },
  header: {
    backgroundColor: 'white',
    height: headH,
    paddingTop: px2dp(isIOS ? 30 : 10),
    paddingHorizontal: 16,
  },
  searchBtn: {
    borderRadius: 3,
    height: InputHeight,
    flexDirection: 'row',
    backgroundColor: '#fff',
    justifyContent: 'center',
    alignItems: 'center',
  },
  grid: {
    justifyContent: 'space-around',
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  iconView: {
    position: 'absolute',
    bottom: 16,
    right: 16,
    width: 50,
    height: 50,
  },
  iconViewWrap: {
    justifyContent: 'center',
    alignItems: 'center',
    width: 42,
    height: 42,
    borderColor: '#e5e5e5',
    backgroundColor: 'white',
    borderRadius: 24,
    borderWidth,
    elevation: 5, // for android
    shadowOffset: { width: 0, height: 0 },
    shadowColor: '#e5e5e5',
    shadowOpacity: 0.85,
    shadowRadius: 5,
  },
  count: {
    backgroundColor: '#e23f3c',
    height: 14,
    borderRadius: 8,
    overflow: 'hidden',
    paddingHorizontal: 4,
    alignItems: 'center',
    position: 'absolute',
    top: 0,
    right: 0,
    zIndex: 9999,
  },
})

export default GoodsList
